package nckd.wnqjt.tmc.tda.plugin.form;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

import com.alibaba.fastjson.JSON;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.qing.*;
import kd.bos.form.IPageCache;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;

/**
 * @author husheng
 * @date 2024-11-04 11:55
 * @description 动态表单插件      担保人分布
 */
public class GuaranteeorgQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    /**
     * 定义轻分析表头
     */
    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "gm_guaranteecontract";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("PK"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("资金组织"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.Date.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("guaranteetype");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("担保人类型"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("amount");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("总额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("seq");
        column.setFieldType(QingFieldType.Int.toNumber());
        column.setName(new LocaleString("seq"));
        meta.addColumn(column);

        return meta;
    }

    /**
     * 获取轻分析数据，通过拿到过滤条件可以重新定义取数逻辑
     */
    @Override
    public QingData getData(String s, int i, int i1) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }

        // 查询担保合同
        String guaranteecontractSql = "id,org.id orgId,org.name orgName,org.number orgNumber,bizdate," +
                "entry_guaranteeorg.a_guaranteeorg,entry_guaranteeorg.a_gratio";
        QFilter filter1 = new QFilter("billstatus", QCP.equals, "C");
        DataSet gmGuaranteecontract = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteecontract", guaranteecontractSql, filter1.toArray(), null);

        /**
         * 0 江西省建材集团有限公司
         * C01	万年青水泥股份本部
         * C010301	南方万年青本部
         * C0108	德安万年青本部
         */
        DynamicObject dynamicObject1 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "0")});
        DynamicObject dynamicObject2 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "C01")});
        DynamicObject dynamicObject3 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "C010301")});
        DynamicObject dynamicObject4 = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, "C0108")});

        // 根据担保人类型分类
        DataSet guaranteecontract1 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject1.getLong("id"));
        DataSet guaranteecontract2 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject2.getLong("id"));
        DataSet guaranteecontract3 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject3.getLong("id"));
        DataSet guaranteecontract4 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg = " + dynamicObject4.getLong("id"));
        DataSet guaranteecontract5 = gmGuaranteecontract.copy().filter("entry_guaranteeorg.a_guaranteeorg not in (" + dynamicObject1.getLong("id") + "," + dynamicObject2.getLong("id") + "," + dynamicObject3.getLong("id") + "," + dynamicObject4.getLong("id") + ")");

        // 担保占用
        //kd.tmc.gm.formplugin.contract.GuaranteeContractUseEdit.loadGuaranteeContractUse
        QFilter gQF = new QFilter("billstatus", "=", "C")
                .and("gdebtstartdate", QCP.less_equals, this.getCurrentDate())
                .and("gratio",QCP.not_equals, BigDecimal.ZERO)
                .and("gdebtbalance",QCP.not_equals, BigDecimal.ZERO)
                .and(new QFilter("gsrcbilltype", QCP.not_equals, "cdm_payablebill")
                        .or("gdebtenddate", QCP.is_null, null)
                        .or("gdebtenddate", QCP.large_than, this.getCurrentDate()));
        DataSet gcUseBills = QueryServiceHelper.queryDataSet(this.getClass().getName(), "gm_guaranteeuse", "id,gcontract.id gcontractId,gdebtbalance", gQF.toArray(), null);
        DataSet finish = gcUseBills.groupBy(new String[]{"gcontractId"}).sum("gdebtbalance").finish();

        DataSet finish1 = guaranteecontract1.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish2 = guaranteecontract2.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish3 = guaranteecontract3.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish4 = guaranteecontract4.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();
        DataSet finish5 = guaranteecontract5.join(finish.copy()).on("id", "gcontractId").select(gmGuaranteecontract.getRowMeta().getFieldNames(), new String[]{"gdebtbalance"}).finish();

        DataSet dataSet1 = finish1.select(new String[]{"id", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'建材集团' as guaranteetype","1 as seq"});
        DataSet dataSet2 = finish2.select(new String[]{"id", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'股份公司' as guaranteetype","2 as seq"});
        DataSet dataSet3 = finish3.select(new String[]{"id", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'南方万年青' as guaranteetype","3 as seq"});
        DataSet dataSet4 = finish4.select(new String[]{"id", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'德安万年青' as guaranteetype","4 as seq"});
        DataSet dataSet5 = finish5.select(new String[]{"id", "orgName", "bizdate", "(entry_guaranteeorg.a_gratio * gdebtbalance / 100) amount", "'其他' as guaranteetype","5 as seq"});

        DataSet dataSet = dataSet1.union(dataSet2, dataSet3, dataSet4, dataSet5);

        QingData data = null;
        if (i < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<>();
            dataindex.put("id", 0);
            dataindex.put("orgName", 1);
            dataindex.put("bizdate", 2);
            dataindex.put("guaranteetype", 3);
            dataindex.put("amount", 4);
            dataindex.put("seq", 5);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<>();
            while (dataSet.hasNext()) {
                Row row = dataSet.next();
                Object[] obj = new Object[6];
                obj[0] = row.getLong("id");
                obj[1] = row.getString("orgName");
                Timestamp timestamp = (Timestamp) row.get("bizdate");
                long time = timestamp.getTime();
                obj[2] = time;
                obj[3] = row.getString("guaranteetype");
                obj[4] = row.getBigDecimal("amount");
                obj[5] = row.getLong("seq");
                rows.add(obj);
            }
            data.setRows(rows);
        }

        return data;
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    private Date getCurrentDate() {
        Calendar cal = new GregorianCalendar();
//        cal.set(11, 0);
//        cal.set(12, 0);
//        cal.set(13, 0);
//        cal.set(14, 0);
        return cal.getTime();
    }
}
